package com.solution.wx.my.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.solution.admin.auth.entity.UserEntity;
import com.solution.admin.auth.service.UserService;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.home.service.RedisService;
import com.solution.admin.point.constants.PointConstants;
import com.solution.admin.point.constants.PointConstants.PointOperateFlag;
import com.solution.admin.point.constants.PointConstants.PointOperateType;
import com.solution.admin.point.service.PointService;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.constants.PublicStatus.USER_APPROVE_STATUS;
import com.solution.common.utils.ip.IPUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.core.constants.WechatConstants;
import com.solution.wx.core.entity.SNSUserEntity;
import com.solution.wx.core.util.WechatUtil;
import com.solution.wx.my.constants.MyConstants;
import com.solution.wx.share.service.ShareInfoService;

/**
 * 微信注册账号控制层
 * @author: solin
 * @date: 2017年11月16日 下午4:57:18
 */
@RequestMapping("/wx/my")
@Controller("wxRegisterController")
public class RegisterController {
	private Logger logger = LoggerFactory.getLogger(RegisterController.class);
	@Autowired
	RedisService redisService;
	@Autowired
	CustomerService customerService;
	@Autowired
	CompanyService companyService;
	@Autowired
	UserService userService;
	
	@Autowired
	ShareInfoService shareInfoService;
	@Autowired
	KeyMapService keyMapService;
	@Autowired
	PointService pointService;
	
	/**
	 * 跳转到注册页面
	 * @param request
	 * @param model
	 * @return
	 * @author: solin
	 * @date: 2017年11月16日 下午3:23:03
	 */
	@RequestMapping("/toRegisterPage")
	public String toRegisterPage(HttpServletRequest request){
		return "wx/my/register";
	}
	
	/**
	 * 跳转到注册填写密码页面
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月19日 下午10:00:00
	 */
	@RequestMapping("/toRegisterPwdPage")
	public String toRegisterPwdPage(HttpServletRequest request, String userName, String mobile, String receiveVerifyCode) {
		request.setAttribute("userName", userName);
		request.setAttribute("mobile", mobile);
		try {
			// redis中的验证码KEY
			String verifyCodeKey = MyConstants.MOBILE_VERIFY_CODE_KEY.concat(IPUtils.getIntenetIP(request));
			// redis中的验证码值
			String sendVerifyCode = redisService.get(verifyCodeKey);
			if (!String.valueOf(receiveVerifyCode).equals(sendVerifyCode)) {
				request.setAttribute(PublicStatus.RESULT_MSG, "验证码不正确！");
				return "wx/my/register";
			}
			// 校验成功后将验证码缓存清空
			redisService.del(verifyCodeKey); 
			
			// 验证手机号是否已经注册
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("mobile", mobile);
			// 获取客户信息
			List<CustomerEntity> customerList = customerService.listCustomer(params);
			for (CustomerEntity customer : customerList) {
				String msg = "";
				if (USER_APPROVE_STATUS.AGREE.getId().equals(customer.getStatus())) {
					msg = "此手机号已经注册!";
				} else if (USER_APPROVE_STATUS.PENDING.getId().equals(customer.getStatus())) {
					// 正在审核中的用户，同样提示已经注册
					msg = "此手机号已经注册!";
				} else if (USER_APPROVE_STATUS.REJECT.getId().equals(customer.getStatus())) { 
					// 审核驳回
					// msg = "此手机号注册已经被管理员审核驳回!";
				}
				if (StringUtil.isNotEmpty(msg)) {
					request.setAttribute(PublicStatus.RESULT_CODE, 0);
					request.setAttribute(PublicStatus.RESULT_MSG, msg);
					return "wx/my/register";
				}
			}
			
			//获取系统用户信息
			params.put("status", USER_APPROVE_STATUS.AGREE.getId());
			List<UserEntity> userList = userService.getUserList(params);
			if ((null == customerList || customerList.size() == 0) && null != userList && userList.size() > 0) {
				request.setAttribute(PublicStatus.RESULT_CODE, 0);
				request.setAttribute(PublicStatus.RESULT_MSG, "此手机号已经注册!");
				return "wx/my/register";
			}
			
			/**
			//将注册使用的用户名和手机号码保存到redis中
			redisService.save(MyConstants.REGISTER_USERNAME_KEY.concat(IPUtils.getIntenetIP(request)), userName, (30 * 60));
			redisService.save(MyConstants.REGISTER_MOBILE_KEY.concat(IPUtils.getIntenetIP(request)), mobile, (30 * 60));
			*/
		} catch (Exception e) {
			logger.error("==>注册失败:{}", e);
			request.setAttribute(PublicStatus.RESULT_CODE, 0);
			request.setAttribute(PublicStatus.RESULT_MSG, "注册失败!");
		}
		
		return "wx/my/register_pwd";
	}
	
	/**
	 * 注册
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月20日 上午9:41:02
	 */
	@RequestMapping("/register")
	public String register(HttpServletRequest request) {
		//从cookie中获取openId
		String openId = WechatUtil.getOpenIdFromCookie(request);
		if (StringUtil.isEmpty(openId)) {
			request.setAttribute(PublicStatus.RESULT_CODE, 0);
			request.setAttribute(PublicStatus.RESULT_MSG, "注册失败,未获取用户OpenId!");
			return "wx/my/register";
		}
		
		//将注册使用的用户名和手机号码从redis中取出
		//String userName = redisService.get(MyConstants.REGISTER_USERNAME_KEY.concat(IPUtils.getIntenetIP(request)));
		//String mobile = redisService.get(MyConstants.REGISTER_MOBILE_KEY.concat(IPUtils.getIntenetIP(request)));
		String userName = request.getParameter("userName");
		String mobile = request.getParameter("mobile");
		String password = request.getParameter("password");
		
		// 公司信息赋值
		CompanyEntity company = new CompanyEntity();
		company.setStatus(STATUS.ENABLED.getId());
		company.setCreater(mobile);
		// 如果公司名称为空
		if (StringUtil.isEmpty(company.getCompanyName())) {
			company.setCompanyName(userName.concat("(").concat(mobile).concat(")"));
		}
		// 保存公司信息
		Long companyId = companyService.saveCompany(company);
		if (companyId > 0) {
			// 保存客户信息
			CustomerEntity customer = new CustomerEntity();
			customer.setOpenId(openId);
			customer.setLoginCode(mobile);
			customer.setUserName(userName);
			customer.setMobile(mobile);
			customer.setPassword(password);
			customer.setCompanyId(companyId);
			customer.setGender(1); // 性别默认为男性
			customer.setDefaultFlag(1); //作为默认联系人
			customer.setStatus(USER_APPROVE_STATUS.PENDING.getId());
			customer.setCreater(customer.getLoginCode());
			// 从redis 里面获取到推荐人的信息
			String parentInvitationCode = shareInfoService.getParentInvitationCode(request.getSession().getId());
			if (StringUtil.isNotNull(parentInvitationCode)) {
				customer.setParentInvitationCode(parentInvitationCode);
			}
			//获取用户头像
			// 从redis中获取通过网页授权获取的用户信息
			String strSNSUserInfoJson = redisService.get(WechatConstants.SNS_USERINFO_KEY.concat(openId));
			SNSUserEntity snsUserInfo = JSONObject.parseObject(strSNSUserInfoJson, SNSUserEntity.class);
			if (null != snsUserInfo) {
				customer.setHeadImage(snsUserInfo.getHeadImgUrl());
			}
			Long customerId = customerService.saveCustomer(customer);
			if (customerId > 0) {
				//注册成功之后跳转到绑定页面等待审核
				request.setAttribute(PublicStatus.RESULT_CODE, 1);
				request.setAttribute(PublicStatus.RESULT_MSG, "恭喜您，注册成功!");
				//跳转到绑定页面
				return "wx/my/bindAccount"; 
			}
		}
		
		request.setAttribute(PublicStatus.RESULT_CODE, 0);
		request.setAttribute(PublicStatus.RESULT_MSG, "注册失败!");
		return "wx/my/register";
	}
}
